package com.hty.filemanager;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SearchActivity extends AppCompatActivity {

    SimpleDateFormat SDF = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    String filepath = "";
    ListView listView;
    EditText editText;
    ImageButton imageButton_clear;
    InputMethodManager IMM;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        IMM = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        listView = findViewById(R.id.listView);
        editText = findViewById(R.id.editText);
        editText.addTextChangedListener(new EditChangedListener());
        imageButton_clear = findViewById(R.id.imageButton_clear);
        imageButton_clear.setOnClickListener(new OnClickListener());
        imageButton_clear.setVisibility(View.GONE);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String path = ((TextView) arg1.findViewById(R.id.textView_path)).getText().toString();
                String mime = URLConnection.getFileNameMap().getContentTypeFor(path);
                if (mime != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new File(path)), mime);
                    startActivity(intent);
                }
            }
        });
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
                IMM.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
                filepath = ((TextView) info.targetView.findViewById(R.id.textView_path)).getText().toString();
                String title = ((TextView) info.targetView.findViewById(R.id.textView_name)).getText().toString();
                menu.setHeaderTitle(title);
                menu.add(0, 0, 0, "复制");
                menu.add(0, 1, 1, "剪切");
                menu.add(0, 2, 2, "重命名");
                menu.add(0, 3, 3, "属性");
                menu.add(0, 4, 4, "分享");
                menu.add(0, 5, 5, "删除");
                menu.add(0, 6, 6, "编辑");
                menu.add(0, 7, 7, "打开文件所在位置");
            }
        });

    }

    String queryPathByID(int id) {
        Uri uri = MediaStore.Files.getContentUri("external");
        String[] projection = new String[] { MediaStore.Files.FileColumns.DATA };
        String selection = MediaStore.Files.FileColumns._ID + "=?";
        String[] selectionArgs = new String[] { String.valueOf(id) };
        Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);
        String path = "";
        if (cursor.moveToFirst()) {
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
        }
        cursor.close();
        //Log.e(Thread.currentThread().getStackTrace()[2] + "", id + ", " + path);
        return path;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        //AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        String filename = filepath.substring(filepath.lastIndexOf(File.separator)+1);
        switch (item.getItemId()) {
            case 0:
                Toast.makeText(getApplicationContext(), "复制", Toast.LENGTH_SHORT).show();
                break;
            case 1:
                Toast.makeText(getApplicationContext(), "剪切", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                final EditText editText = new EditText(SearchActivity.this);
                editText.setText(filename);
                AlertDialog.Builder dialog = new AlertDialog.Builder(SearchActivity.this);
                dialog.setTitle("重命名").setView(editText);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String path1 = filepath.substring(0, filepath.lastIndexOf(File.separator)) + File.separator + editText.getText().toString();
                        File file = new File(filepath);
                        boolean b = file.renameTo(new File(path1));
                        if (b) {
                            ContentValues values = new ContentValues();
                            values.put(MediaStore.Files.FileColumns.DATA, path1);
                            getContentResolver().update(MediaStore.Files.getContentUri("external"), values, MediaStore.Files.FileColumns.DATA + "=?", new String[]{ filepath });
                            //刷新ListView
                            //cursor.requery();
                            //adapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(SearchActivity.this, "重命名失败:\n" + path1, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
                break;
            case 3:
                File file = new File(filepath);
                String mime = URLConnection.getFileNameMap().getContentTypeFor(filepath);
                Date datec = new Date(file.lastModified());
                new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("属性").setMessage("文件路径：" + filepath + "\n创建时间：" + SDF.format(datec) + "\n类型：" + mime + "\n大小：" + Formatter.formatFileSize(this, file.length())).setPositiveButton("确定", null).show();
                break;
            case 4:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filepath)));
                intent.setType("*/*");
                startActivity(Intent.createChooser(intent, "分享 " + filename));
                break;
            case 5:
                file = new File(filepath);
                if (file.exists()) {
                    boolean b = file.delete();
                    if (b) {
                        getContentResolver().delete(MediaStore.Files.getContentUri("external"), MediaStore.Files.FileColumns.DATA + "=?", new String[]{ filepath });
                        //不需要刷新ListView？
                        //cursor.requery();
                        //adapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(SearchActivity.this, "删除失败！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    getContentResolver().delete(MediaStore.Files.getContentUri("external"), MediaStore.Files.FileColumns.DATA + "=?", new String[]{ filepath });
                }
                break;
            case 6:
                intent = new Intent(SearchActivity.this, TexteditActivity.class);
                intent.putExtra("Path", filepath);
                startActivity(intent);
                break;
            case 7:
                intent = new Intent(SearchActivity.this, MainActivity.class);
                intent.putExtra("Path", filepath);
                startActivity(intent);
                break;
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {

        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().equals("")) {
                imageButton_clear.setVisibility(View.GONE);
                listView.setAdapter(null);
            } else {
                imageButton_clear.setVisibility(View.VISIBLE);
                search(s.toString());
            }
        }
    }

    class OnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.imageButton_clear:
                    editText.setText("");
                    break;
            }
        }
    }

    void search(String s) {
        String[] projection = new String[]{ MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.DATE_MODIFIED, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns._ID };
        Cursor cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"), projection, MediaStore.Files.FileColumns.DATA + " LIKE ?", new String[]{ "%" + s + "%" }, MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC");
        int count = cursor.getCount();
        setTitle("搜索 " + count);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, new String[] { MediaStore.Video.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DATE_MODIFIED, MediaStore.Video.Media._ID }, new int[] { R.id.textView_path, R.id.textView_name, R.id.textView_size, R.id.textView_time, R.id.imageView_icon }, CursorAdapter.FLAG_AUTO_REQUERY);
        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            String path = "";
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
                //Log.e(Thread.currentThread().getStackTrace()[2] + "", view.toString() + columnIndex);
                if (view.getId() == R.id.textView_name) {
                    path = cursor.getString(columnIndex);
                    ((TextView) view).setText(path.substring(path.lastIndexOf("/") + 1));
                    return true;
                } else if (view.getId() == R.id.textView_size) {
                    long filesize = cursor.getLong(columnIndex);
                    ((TextView) view).setText(Formatter.formatFileSize(SearchActivity.this, filesize));
                    return true;
                } else if (view.getId() == R.id.textView_time) {
                    Date date = new Date(cursor.getLong(columnIndex) * 1000);
                    ((TextView) view).setText(SDF.format(date));
                    return true;
                } else if (view.getId() == R.id.imageView_icon) {
                    String mime = URLConnection.getFileNameMap().getContentTypeFor(path);
                    if (mime == null) {
                        ((ImageView) view).setImageResource(R.mipmap.file);
                    } else if (mime.startsWith("video/")) {
                        int id = cursor.getInt(columnIndex);
                        Bitmap bitmap = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(), id, MediaStore.Video.Thumbnails.MINI_KIND, null);
                        if (bitmap != null)
                            ((ImageView) view).setImageBitmap(bitmap);
                        else
                            ((ImageView) view).setImageResource(R.mipmap.video);
                    } else if (mime.startsWith("image/")) {
                        int id = cursor.getInt(columnIndex);
                        Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), id, MediaStore.Images.Thumbnails.MINI_KIND, null);
                        if (bitmap != null)
                            ((ImageView) view).setImageBitmap(bitmap);
                        else
                            ((ImageView) view).setImageResource(R.mipmap.image);
                    }  else if (mime.startsWith("audio/")) {
                        ((ImageView) view).setImageResource(R.mipmap.audiofile);
                    } else if (mime.equals("text/plain")) {
                        ((ImageView) view).setImageResource(R.mipmap.txtfile);
                    } else if (mime.equals("text/html")) {
                        ((ImageView) view).setImageResource(R.mipmap.htmlfile);
                    } else if (mime.equals("application/msword")) {
                        ((ImageView) view).setImageResource(R.mipmap.docfile);
                    } else if (mime.equals("application/pdf")) {
                        ((ImageView) view).setImageResource(R.mipmap.pdffile);
                    } else if (mime.equals("application/x-tar") || mime.equals("application/zip") || mime.equals("application/x-gzip")) {
                        ((ImageView) view).setImageResource(R.mipmap.zipfile);
                    } else {
                        ((ImageView) view).setImageResource(R.mipmap.file);
                    }
                    return true;
                }
                return false;
            }
        });
        listView.setAdapter(adapter);
    }

}